package com.zsr.example.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.zsr.example.config.VodConfigProperties;
import com.zsr.example.config.exception.CommonJsonException;
import com.zsr.example.service.VodService;
import com.zsr.example.util.AliyunVodSDKUtils;
import com.zsr.example.util.constants.ErrorEnum;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.MultimediaInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 视频上传实现类
 *
 * @author zsr
 * @date 2021/6/16 9:21
 */
@Service
@Slf4j
public class VodServiceImpl implements VodService {
    @Override
    public Map<String, Object> uploadAly(MultipartFile multipartFile) {
        Map<String, Object> result = new HashMap<>();
        try {
            InputStream inputStream = multipartFile.getInputStream();
            String originalFilename = multipartFile.getOriginalFilename();
            String title = originalFilename.substring(0, originalFilename.lastIndexOf("."));

            //TODO 加密上传
            UploadStreamRequest request = new UploadStreamRequest(
                    VodConfigProperties.ACCESS_KEY_ID,
                    VodConfigProperties.ACCESS_KEY_SECRET,
                    title, originalFilename, inputStream);
            System.out.println(VodConfigProperties.ACCESS_KEY_SECRET);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。
            // 其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            String videoId = response.getVideoId();
            if (!response.isSuccess()) {
                //SDK.ServerUnreachable
                //Server unreachable: java.net.MalformedURLException: no protocol: 127.0.0.1:7890
                String errorMessage = "阿里云上传错误：" + "code：" + response.getCode() + ", message：" + response.getMessage();
                log.warn(errorMessage);
                if (StringUtils.isEmpty(videoId))
                    throw new CommonJsonException(ErrorEnum.E_20001);
            } else {
                Encoder encoder = new Encoder();

                // 选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
                File file;
                //String[] filename = multipartFile.getOriginalFilename().split(".");
                String filename=multipartFile.getOriginalFilename();
                int i = filename.lastIndexOf(".");
                String prefix = filename.substring(0, i);
                String suffix = filename.substring(i, filename.length());
                file = File.createTempFile( prefix,  suffix);
                multipartFile.transferTo(file);
                //FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
                MultimediaInfo m = encoder.getInfo(file);
                file.deleteOnExit();

                long ls = m.getDuration() / 1000;
                /*int hour = (int) (ls / 3600);
                int minute = (int) (ls % 3600) / 60;
                int second = (int) (ls - hour * 3600 - minute * 60);
                String length = hour + ":" + minute + ":" + second + ":";
                result.put("videoLengthString", length);//视频时长字符串*/
                result.put("duration", ls);//视频时长字符串

            }
            result.put("videoId", videoId);


        } catch (IOException e) {
            throw new CommonJsonException(ErrorEnum.E_80004);

        } catch (EncoderException e) {
            e.printStackTrace();
        }
        return result;
    }


    @Override
    public void removeVideo(String videoId) {
        try {
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(
                    VodConfigProperties.ACCESS_KEY_ID,
                    VodConfigProperties.ACCESS_KEY_SECRET);

            DeleteVideoRequest request = new DeleteVideoRequest();

            request.setVideoIds(videoId);

            DeleteVideoResponse response = client.getAcsResponse(request);

            //System.out.print("RequestId = " + response.getRequestId() + "\n");

        } catch (ClientException e) {
            throw new CommonJsonException(ErrorEnum.E_20001);
        }
    }

    //删除多个视频
    @Override
    public boolean removeVideoList(List<String> videoIdList) {
        try {
            // 初始化对象
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(VodConfigProperties.ACCESS_KEY_ID,
                    VodConfigProperties.ACCESS_KEY_SECRET);
            // 创建删除视频request对象
            DeleteVideoRequest request = new DeleteVideoRequest();

            // videoIdList值转成 1,2,3
            String videoIds = String.join(",", videoIdList);

            // 向request设置视频id
            request.setVideoIds(videoIds);
            // 调用初始化对象的方法实现删除
            client.getAcsResponse(request);
            return true;
        } catch (ClientException e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
            return false;
        }
    }
}
